import { fork } from 'child_process'
import path from 'path'
import { LogMessage } from './LogType'
import { LogResult } from './logResult'
import { ipcMain } from 'electron'

let logProcess: ReturnType<typeof fork> | null = null;
let isLogging = false;

ipcMain.on('log-message', (event, logData) => {
  console.log('Received log from renderer:', logData);
  if (logProcess && isLogging) {
    logProcess.send({ command: 'log', log: logData });
  }
});

export default async function installLog(): Promise<void> {
  ipcMain.handle('startLogCollection', async (_event, log?: LogMessage) => {
    // console.log('startLogCollection')
    if (logProcess) {
      return { success: false, error: '日志采集已运行' }; 
    }
    
    logProcess = fork(path.join(__dirname, 'logWorker.js'));
    isLogging = true;
    
    return new Promise((resolve) => {
      logProcess?.send({ command: 'start', log });
      logProcess?.once('message', (msg: LogResult) => {
        resolve(msg.success 
          ? { success: true, result: '日志采集已启动' } 
          : { success: false, error: msg.error }
        );
      });
      logProcess?.on('error', (err) => {
        resolve({ success: false, error: `日志进程错误: ${err.message}` });
      });
    });
  });

  ipcMain.handle('stopLogCollection', async () => {
    if (!logProcess) {
        return { success: false, error: '日志采集未运行' };
    }

    isLogging = false;

    return new Promise((resolve) => {
        logProcess?.send({ command: 'stop' });

        // 等待子进程返回确认消息后再 kill
        logProcess?.once('message', (msg: LogResult) => {
            logProcess?.kill(); // 确保子进程退出
            logProcess = null;
            resolve({ success: true, result: '日志采集已停止' });
        });

        // 超时后备方案
        setTimeout(() => {
            logProcess?.kill();
            logProcess = null;
            resolve({ success: false, error: '停止日志超时' });
        }, 3000); // 3 秒超时
    });
  });
}